package com.why.blog.admin.upload;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName UploadController.java
 * @Description 上传文件
 * @createTime 2019年05月06日 19:04:00
 */
@Controller
@RequestMapping("/upload")
public class UploadController {

    private static final String SUCCESS = "success";
    @PostMapping("/uploadFile")
    @ResponseBody
    public JSON test(@RequestParam("editormd-image-file") MultipartFile uploadFile, HttpServletRequest request) throws IOException {
        File tempFile = null;
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject resultJs=new JSONObject();
        try {
            request.getSession().getServletContext().getRealPath("xls");
            String filename = uploadFile.getOriginalFilename();
            String url = "http://crawler_upload.6ack.com/upload";
            RestTemplate restTemplate = new RestTemplate();
            //设置请求头
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("multipart/form-data");
            headers.setContentType(type);

            //生成本地缓存路径
            String localPath = getFilePath(filename);
            //缓存文件
            tempFile = new File(localPath);
            try {
                uploadFile.transferTo(tempFile);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("缓存文件失败");
            }

            FileSystemResource fileSystemResource = new FileSystemResource(tempFile);

            //设置请求体，注意是LinkedMultiValueMap
            MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
            form.add("file", fileSystemResource);
            //封装
            HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
            ResponseEntity<Object> object = restTemplate.exchange(url, HttpMethod.POST, files, Object.class);
            Object o = object.getBody();
            Map result = (Map) object.getBody();
            resultJs.put("success", 1);
            resultJs.put("message", "上传成功");
            resultJs.put("url", result.get("message"));
            return resultJs;
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (tempFile != null && tempFile.exists()) {
                tempFile.delete();
            }
        }
        return resultJs;
    }

    public String getFilePath(String sourceFileName) {
        String baseFolder = "C:/images" + File.separator + "images";
        Date nowDate = new Date();
        // yyyy/MM/dd
        String fileFolder = baseFolder + File.separator + new DateTime(nowDate).toString("yyyy")
                + File.separator + new DateTime(nowDate).toString("MM") + File.separator
                + new DateTime(nowDate).toString("dd");
        File file = new File(fileFolder);
        if (!file.isDirectory()) {
            // 如果目录不存在，则创建目录
            file.mkdirs();
        }
        // 生成新的文件名
        String fileName = new DateTime(nowDate).toString("yyyyMMddhhmmssSSSS")
                + RandomUtils.nextInt(100, 9999) + "." + StringUtils.substringAfterLast(sourceFileName, ".");
        return fileFolder + File.separator + fileName;
    }

//    public String upload(HttpSession session, @RequestParam(value = "editormd-image-file") MultipartFile file) {
//        JSONObject res = new JSONObject();
//        try {
//            Map<String, String> uploadMap = QiniuUtils.upload(file.getInputStream());
//            String code = uploadMap.get("code");
//            if (SUCCESS.equals(code)) {
//                res.put("success", 1);
//                res.put("message", "上传成功");
//                res.put("url", uploadMap.get("url"));
//            } else {
//                res.put("success", 0);
//                res.put("message", "上传失败" + uploadMap.get("error"));
//            }
//        } catch (IOException e) {
//            res.put("success", 0);
//            res.put("message", "上传异常");
//        }
//        return res.toString();
//    }
}
